package com.xiaoxin.executor.batch.listener;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.batch.core.JobParameter;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
public class EtlJobLogListener implements JobExecutionListener {
	private static Logger logger = LogManager.getLogger(EtlJobLogListener.class);

	public void beforeJob(JobExecution jobExecution) {
		String jobName = jobExecution.getJobInstance().getJobName();
		Date createTime = jobExecution.getCreateTime();
		Map<String, JobParameter> parameters = jobExecution.getJobParameters().getParameters();
		logger.info("Job begin. [jobName:{}] [createTime:{}] [parameters:{}]", jobName, createTime, parameters);
	}

	public void afterJob(JobExecution jobExecution) {
		String jobName = jobExecution.getJobInstance().getJobName();
		BatchStatus status = jobExecution.getStatus();
		Date endTime = jobExecution.getEndTime();
		logger.info("Job end. [jobName:{}] [status:{}] [endTime:{}] []", jobName, status, endTime);

		List<Throwable> failureExceptions = jobExecution.getAllFailureExceptions();
		for (Throwable exception : failureExceptions) {
			logger.error(exception.getMessage(), exception);
		}
	}

}
